package com.cgwx.aop.exception;


import com.cgwx.aop.result.Result;
import com.cgwx.aop.result.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.RestClientException;

import java.util.List;

@Slf4j
@RestControllerAdvice
public class ExceptionHandle {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    Result handleBindException(MethodArgumentNotValidException exception)
    {
        String message = "";
        BindingResult bindingResult = exception.getBindingResult();
        if(bindingResult.hasErrors())
        {
            List<ObjectError> errorList = bindingResult.getAllErrors();
            for(ObjectError objectError : errorList)
            {
                FieldError fieldError = (FieldError) objectError;
                message += fieldError.getDefaultMessage() + " ";
            }
            message = message.trim();
        }

        return ResultUtil.error(500,message);
    }
    @ExceptionHandler(RestClientException.class)
    public Result doHandleArithmeticException(RestClientException e){
        return ResultUtil.error(501,"user service connect error");
    }



}
